/*******************************************************************************

    
    Cloud Firewall - a browser extension/addon that allows users to block connections 
    to sites, pages and web resources (images, videos, etc) hosted in major cloud services
    if the user wishes to do so.
    Copyright (C) 2019 Niklas Poslovski
    Copyright (C) 2019 Gokulakrishna Sudharsan

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

    Home: https://notabug.org/nipos/cloud-firewall
*/

/* globals PopupApp */
var DOM = {};
DOM.popupDOM = {};

var PopupApp = window.PopupApp || {};

DOM.popupDOM.updateDOM = () => {
  //temporary fix until css adjusted

  // temporary duplicate of stats table as I don't yet have the time to do bootstrap classes things
  // ... to push left column table to bottom of screen in android firefox screen
  if (navigator.userAgent.match(/Android/i)) {
    document.getElementById("tableMain").style =
      "width: 220px; margin: 10px auto;";
    let statsTableDesktop = document.getElementById("statsTableDesktop");
    if (!!statsTableDesktop) {
      statsTableDesktop.remove();
    }
    /*let br2 = document.getElementById("2BR");
    if (!!br2) {
      br2.remove();
    }*/
  } else {
    let statsTableAndroid = document.getElementById("statsTableAndroid");
    if (!!statsTableAndroid) {
      statsTableAndroid.remove();
    }
  }

  //console.log("error in removing the temporary 2nd stats block")

  // try {
  /*  if (PopupApp.disabled) {
      document.querySelector("#showdisablebutton").style.display = "none";
      document.querySelector("#showenablebutton").style.display = "";
    } else {
      document.querySelector("#showdisablebutton").style.display = "";
      document.querySelector("#showenablebutton").style.display = "none";
    }*/
	
var timestring = browser.i18n.getMessage('time');

  for (let company in PopupApp.settingsToggles) {
    if (company === "notInList") {
      continue;
    }
    let id = "#switch" + company;
    document.querySelector(id).checked = PopupApp["settingsToggles"][company];
  }

  document.querySelector("#versiondisplay").textContent = !!PopupApp.appVersion
    ? "Version " + PopupApp.appVersion
    : "Version 1.1";
  // Dont want to show NAN  in UI, rather be zero and have user reach out if counter not updating
  var total =
    (PopupApp.counts.amazon || 0) +
    (PopupApp.counts.google || 0) +
    (PopupApp.counts.facebook || 0) +
    (PopupApp.counts.microsoft || 0) +
    (PopupApp.counts.apple || 0) +
    (PopupApp.counts.cloudflare || 0);
  if (total === 0) {
    document.querySelector("#showstats").style.display = "none";
  } else {
    if (PopupApp.counts.google > 0) {
      let count = PopupApp.counts.google || 0;
      document.querySelector(
        "#countsgoogle"
      ).textContent = "Google: " + count + timestring;
    } else {
      document.querySelector("#countsgoogle").style.display = "none";
    }

    if (PopupApp.counts.amazon > 0) {
      let count = PopupApp.counts.amazon || 0;

      document.querySelector(
        "#countsamazon"
      ).textContent = "Amazon: " + count + timestring;
    } else {
      document.querySelector("#countsamazon").style.display = "none";
    }

    if (PopupApp.counts.facebook > 0) {
      let count = PopupApp.counts.facebook || 0;
      document.querySelector(
        "#countsfacebook"
      ).textContent = "Facebook: " + count + timestring;
    } else {
      document.querySelector("#countsfacebook").style.display = "none";
    }

    if (PopupApp.counts.microsoft > 0) {
      let count = PopupApp.counts.microsoft || 0;
      document.querySelector(
        "#countsmicrosoft"
      ).textContent = "Microsoft: " + count + timestring;
    } else {
      document.querySelector("#countsmicrosoft").style.display = "none";
    }

    if (PopupApp.counts.apple > 0) {
      let count = PopupApp.counts.apple || 0;
      document.querySelector(
        "#countsapple"
      ).textContent = "Apple: " + count + timestring;
    } else {
      document.querySelector("#countsapple").style.display = "none";
    }
    if (PopupApp.counts.cloudflare > 0) {
      let count = PopupApp.counts.cloudflare || 0;
      document.querySelector(
        "#countscloudflare"
      ).textContent = "Cloudflare: " + count + timestring;
    } else {
      document.querySelector("#countscloudflare").style.display = "none";
    }
    /*for(let company in PopupApp.counts){
    if(company === "notInList"){
      continue;}
  DOM.popupDOM.showCounts(company);
} */
    /*document.querySelector("#countsamazon").textContent = "Amazon : " + PopupApp.counts.amazon + " times";
document.querySelector("#countsfacebook").textContent = "Facebook : " + PopupApp.counts.facebook + " times";
document.querySelector("#countsmicrosoft").textContent = "Microsoft : " + PopupApp.counts.microsoft + " times";
document.querySelector("#countsapple").textContent = "Apple : " + PopupApp.counts.apple + " times";
*/
    document.querySelector("#countstotal").textContent =
	  browser.i18n.getMessage('total') + ": " + total + " " + browser.i18n.getMessage('connections');
  }
  let hostnameToDisplay = document.getElementById("hostnameToDisplay");
  let hname = PopupApp.hostname;
  hname = hname.startsWith("www.") ? hname.replace("www.", "") : hname;
  if (!!hostnameToDisplay) {
    if (hname.length > 0 && hname.includes(".")) {
      hostnameToDisplay.textContent =
        "From" + String.fromCharCode(160) + hname + ":";
    } else {
      hostnameToDisplay.style.display = "none";
    }
  }
  if (total < 1) {
    let a = document.querySelector("#statsTableDesktop");
    if (!!a) {
      a.style.display = "none";
    }
    //console.log(PopupApp.urlFromQuery);
    if (
      !!a &&
      (PopupApp.urlFromQuery.startsWith("about:") ||
        PopupApp.urlFromQuery.startsWith("moz-ext"))
    ) {
      a.style.display = "none";
    }
    let b = document.querySelector("#statsTableAndroid");
    if (!!b) {
      b.style.display = "none";
    }
    if (
      !!b &&
      (PopupApp.urlFromQuery.startsWith("about:") ||
        PopupApp.urlFromQuery.startsWith("moz-ext"))
    ) {
      b.style.display = "none";
    }
  }
  // Dont want to show NAN  in UI, rather be zero and have user reach out if counter not updating
  //try {
  var perPagetotal =
    (PopupApp.perPageStats.amazon || 0) +
    (PopupApp.perPageStats.google || 0) +
    (PopupApp.perPageStats.facebook || 0) +
    (PopupApp.perPageStats.microsoft || 0) +
    (PopupApp.perPageStats.apple || 0) +
    (PopupApp.perPageStats.cloudflare || 0);
  if (!PopupApp.isCFEnabled) {
    perPagetotal = 0;
  }
  if (PopupApp.perPageStats.google > 0) {
    //&& PopupApp.settingsToggles.google) {
    let count = PopupApp.perPageStats.google || 0;
    document.querySelector(
      "#pagecountsgoogle"
    ).textContent = "Google: " + count + timestring;
  } else {
    document.querySelector("#pagecountsgoogle").style.display = "none";
  }

  if (PopupApp.perPageStats.amazon > 0) {
    //} && PopupApp.settingsToggles.amazon) {
    let count = PopupApp.perPageStats.amazon || 0;

    document.querySelector(
      "#pagecountsamazon"
    ).textContent = "Amazon: " + count + timestring;
  } else {
    document.querySelector("#pagecountsamazon").style.display = "none";
  }

  if (PopupApp.perPageStats.facebook > 0) {
    //&& PopupApp.settingsToggles.facebook) {
    let count = PopupApp.perPageStats.facebook || 0;
    document.querySelector(
      "#pagecountsfacebook"
    ).textContent = "Facebook: " + count + timestring;
  } else {
    document.querySelector("#pagecountsfacebook").style.display = "none";
  }

  if (PopupApp.perPageStats.microsoft > 0) {
    //&&    PopupApp.settingsToggles.microsoft
    let count = PopupApp.perPageStats.microsoft || 0;
    document.querySelector(
      "#pagecountsmicrosoft"
    ).textContent = "Microsoft: " + count + timestring;
  } else {
    document.querySelector("#pagecountsmicrosoft").style.display = "none";
  }

  if (PopupApp.perPageStats.apple > 0) {
    //} && PopupApp.settingsToggles.apple) {
    let count = PopupApp.perPageStats.apple || 0;
    document.querySelector(
      "#pagecountsapple"
    ).textContent = "Apple: " + count + timestring;
  } else {
    document.querySelector("#pagecountsapple").style.display = "none";
  }
  if (PopupApp.perPageStats.cloudflare > 0) {
    /*&&
    PopupApp.settingsToggles.cloudflare*/
    let count = PopupApp.perPageStats.cloudflare || 0;
    document.querySelector(
      "#pagecountscloudflare"
    ).textContent = "Cloudflare: " + count + timestring;
  } else {
    document.querySelector("#pagecountscloudflare").style.display = "none";
  }
  let perpagestattotal = document.querySelector("#pagecountstotal");
  if (perPagetotal > 0) {
    //&& PopupApp.isCFEnabled) {
    perpagestattotal.textContent = browser.i18n.getMessage('total') + ": " + perPagetotal + " " + browser.i18n.getMessage('connections');
  } else {
    perpagestattotal.textContent = browser.i18n.getMessage('noconnectionblocked');
    document.querySelector("#copyBtnArea").style.display = "none";
  }

  if (!!PopupApp.domainname && PopupApp.domainname.includes(".")) {
    if (PopupApp.isDomainExcluded) {
      //Uncomment this block once a resolution for this ticket in Mozilla bugtracker
      //https://bugzilla.mozilla.org/show_bug.cgi?id=1546473

      /* for (let i in PopupApp.counts) {
        if (i.toLowerCase().includes("not")) {
          continue;
        }
        let id = "switch" + i;
        document.getElementById(id).disabled = true;
      }
       document.getElementById("blockAllButton").style.display = "none";
        document.getElementById("allowAllButton").style.display = "none";
*/
      document.getElementById("openExcludePopup").style.display = "none";
      document.getElementById("removeFromExcludes").style.display = "";
      //document.getElementById("onthispagetitle").style.display = "none";
      document.getElementById("hostnameToDisplay").style.display = "none";
      /*perpagestattotal.textContent =
          "Note: You disabled rules for " + PopupApp.domainname + "!";
      */
      document.getElementById("inExcludesAlertWrapper").style.display = "";
      document.getElementById("inExcludesAlert").style.display = "";
      document.getElementById("inExcludesAlert").textContent =
        browser.i18n.getMessage('disabledhere');
    } else {
      document.getElementById("blockAllButton").style.display = "";
      document.getElementById("allowAllButton").style.display = "";
      let alert = document.getElementById("inExcludesAlertWrapper");
      alert.style.display = "none";

      //alert.innerText = "Your rules enabled for" + PopupApp.domainname;
      //alert.classList = "";

      for (let i in PopupApp.counts) {
        if (i.toLowerCase().includes("not")) {
          continue;
        }
        let id = "switch" + i;
        document.getElementById(id).disabled = false;
      }
      document.getElementById("openExcludePopup").style.display = "";
      document.getElementById("removeFromExcludes").style.display = "none";
      // document.getElementById("onthispagetitle").style.display = "";
      document.getElementById("hostnameToDisplay").style.display = "";
    }
  }
if(PopupApp.domainname) document.getElementById("infoRule").innerText = browser.i18n.getMessage('customrules');
else document.getElementById("infoRule").innerText = browser.i18n.getMessage('globaldefaultrules');
  /*} catch (e) {
    console.log("error in per page stats " + e.message);
  }*/
  var forstring = browser.i18n.getMessage('for');
  var disablestring = browser.i18n.getMessage('disable');
  var disableforstring = browser.i18n.getMessage('disablefor');
  var enablestring = browser.i18n.getMessage('enable');
  var rulesstring = browser.i18n.getMessage('rules');
  
  if (!!PopupApp.domainname && PopupApp.domainname.includes(".")) {
    if (!PopupApp.isDomainExcluded) {
      document.getElementById("openExcludePopup").textContent =
        disableforstring +
        "\n" +
        PopupApp.domainname;
    } else {
      document.getElementById("removeFromExcludes").textContent =
        enablestring +
        String.fromCharCode(160) +
        forstring +
        "\n" +
        PopupApp.domainname;
    }
  } else {
    if (!!document.getElementById("openExcludePopup")) {
      document.getElementById("openExcludePopup").style.display = "none";
    }
    if (!!document.getElementById("removeFromExcludes")) {
      document.getElementById("removeFromExcludes").style.display = "none";
    }
  }
  /*
  document.getElementById("tableMain").style =
    "width: 220px; margin: 10px auto;";
*/
  if (!!document.getElementsByClassName("hideBody")[0]) {
    document.getElementsByClassName("hideBody")[0].classList = "";
  }
  //updateBadgeText(perPagetotal, PopupApp.tabid);
  /* } catch (e) {
   console.log(e);
    console.log("error probably occured in options.html as we reuse scripts");
  }*/
};

/*
DOM.popupDOM.showCounts = company => {
   let id = "#counts" + company;
let str = company;
  let companyName = str.slice(0, 1).toUpperCase() + str.slice(1, str.length);
  if(PopupApp["counts"]["company"] > 0){
    console.log("87");
    document.querySelector(id).textContent = companyName +" : " + PopupApp["counts"]["company"] + " times";
  }
  else{
      document.querySelector(id).style.display = "none";

  }
} */

DOM.popupDOM.toggleStats = toshow => {
  let el = document.querySelector("#showstats");
  if (!!el) {
    if (toshow) {
      el.style.display = "none";
    } else {
      el.style.display = "";

      if (PopupApp.loadcount > 0) {
        let loadcount = document.querySelector("#loadcount");
        loadcount.style.display = "";
        loadcount.textContent = browser.i18n.getMessage('pagesredirected') + ": " + PopupApp.loadcount;
      }

      if (PopupApp.savecount > 0) {
        let count = document.querySelector("#savecount");
        count.style.display = "";
        count.textContent = browser.i18n.getMessage('pagessavedto') + " WM: " + PopupApp.savecount;
      }
      if (PopupApp.loadcount > 0 && PopupApp.savecount > 0) {
        let count = document.querySelector("#totalcount");
        count.style.display = "";
        count.textContent =
          browser.i18n.getMessage('totalwmvisits') + ": " + `${PopupApp.savecount + PopupApp.loadcount}`;

        if (PopupApp.loadcount !== PopupApp.savecount) {
          let count = document.querySelector("#ratiocount");
          count.style.display = "";
          count.textContent =
			browser.i18n.getMessage('savedredirected') +
            ": " +
            `${((PopupApp.savecount / PopupApp.loadcount) * 100).toFixed(1)}` +
            "%";
        }
      }
      if (PopupApp.loadcount === 0 && PopupApp.savecount === 0) {
        document.querySelector("#welcomecount").style.display = "";
        el.style.display = "";
        document.querySelector("#totalcount").style.display = "none";
        document.querySelector("#ratiocount").style.display = "none";
        document.querySelector("#savecount").style.display = "none";
        document.querySelector("#loadcount").style.display = "none";
      }
    }
  }
};

DOM.popupDOM.keyUpListener = function(e) {
  if (e.keyCode === 13 || e.key === "Enter") {
    switch (e.target.id) {
      case "selectorInput":
        PopupApp.loadAll1pLinks(e.target.value);

        e.target.value = "";
        e.target.parentElement.disabled = true;
        break;
    }
  }
};

DOM.popupDOM.shouldPluralize = (string, count) => {
  if (count > 1) {
    string = string + "s";
    return string;
  }
  return string;
};